package com.youtills.core.config;

import com.youtills.core.lang.StringUtil;

import java.io.IOException;
import java.util.Properties;

/**
 * Created by IntelliJ IDEA.
 * User: ravi
 * Date: 8/24/12
 * Time: 10:02 PM
 * To change this template use File | Settings | File Templates.
 */
public class ConfigLoader {
    private static final ClassLoader CLASS_LOADER = ConfigLoader.class.getClassLoader();

    private static final ConfigLoader instance = new ConfigLoader();

    private Properties properties;

    private ConfigLoader() {
        properties = new Properties();
        String environment = System.getProperty("config.environment");
        if(!StringUtil.isEmpty(environment)){
            load(environment + ".properties", false);
        }

    }

    private synchronized void load(String propertiesFile, boolean reload){
        try {
            Properties old = new Properties();
            old.putAll(properties);
            properties.load(CLASS_LOADER.getResourceAsStream(propertiesFile));
            if(!reload){
                old.putAll(properties);
            }
            properties = old;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String getProperty(String key, String defaultValue){
        return properties.getProperty(key, defaultValue);
    }

    public static String getString(String key){
        return getString(key, null);
    }
    public static String getString(String key, String defaultValue){
        return  instance.getProperty(key, defaultValue);
    }

    public static void loadProperties(String propertiesFile, boolean reload) {
        instance.load(propertiesFile, reload);
    }
}
